/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RateAnalysisPanel.java
 *
 * Created on 2011-10-7, 23:55:55
 */
package com.football.lottery.ui;

import com.football.lottery.obj.FootballLottery;
import com.football.lottery.obj.GameItem;
import com.football.lottery.services.DAOServices;
import java.awt.Color;
import java.awt.GradientPaint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.RefineryUtilities;

/**
 *
 * @author JingWen.Wen
 */
public class OddsAnalysisPanel extends javax.swing.JPanel
{
  private List entryList;
  private ChartFrame chartFrame;
  /** Creates new form RateAnalysisPanel */
  public OddsAnalysisPanel()
  {
    initComponents();
    initData();
    setVisible(true);
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        hitAvgLabel = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        missAvgLabel = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        showButton = new javax.swing.JButton();

        setMinimumSize(new java.awt.Dimension(400, 400));
        setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(new java.awt.BorderLayout());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Index", "Period No.", "Rate Type", "Hit", "Miss"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setMinimumSize(new java.awt.Dimension(75, 75));
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.jTable1.columnModel.title0_1")); // NOI18N
        jTable1.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.jTable1.columnModel.title1_1")); // NOI18N
        jTable1.getColumnModel().getColumn(2).setHeaderValue(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.jTable1.columnModel.title2_1")); // NOI18N
        jTable1.getColumnModel().getColumn(3).setHeaderValue(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.jTable1.columnModel.title3_1")); // NOI18N
        jTable1.getColumnModel().getColumn(4).setHeaderValue(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.jTable1.columnModel.title4")); // NOI18N

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jLabel2.setText(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.jLabel2.text")); // NOI18N
        jPanel1.add(jLabel2);

        hitAvgLabel.setText(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.hitAvgLabel.text")); // NOI18N
        jPanel1.add(hitAvgLabel);

        jLabel1.setText(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.jLabel1.text")); // NOI18N
        jPanel1.add(jLabel1);

        missAvgLabel.setText(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.missAvgLabel.text")); // NOI18N
        jPanel1.add(missAvgLabel);

        jLabel4.setText(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.jLabel4.text")); // NOI18N
        jPanel1.add(jLabel4);

        showButton.setText(org.openide.util.NbBundle.getMessage(OddsAnalysisPanel.class, "OddsAnalysisPanel.showButton.text")); // NOI18N
        showButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showButtonActionPerformed(evt);
            }
        });
        jPanel1.add(showButton);

        jPanel2.add(jPanel1, java.awt.BorderLayout.PAGE_END);

        add(jPanel2, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

  private void showButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_showButtonActionPerformed
  {//GEN-HEADEREND:event_showButtonActionPerformed
    this.displayBarChart(entryList);
  }//GEN-LAST:event_showButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel hitAvgLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel missAvgLabel;
    private javax.swing.JButton showButton;
    // End of variables declaration//GEN-END:variables

  private void initData()
  {
    DAOServices daoServices = new DAOServices();
    List fblList = daoServices.getAllFootballLottery();
    this.entryList = this.getAllEntry(fblList);
    this.addRows(entryList);
  }

  private List getAllEntry(List fblList)
  {
    List list = new ArrayList();
    Iterator fblIt = fblList.iterator();
    int index = 1;
    while (fblIt.hasNext())
    {
      FootballLottery fbl = (FootballLottery) fblIt.next();
      
      String resultStr = fbl.getResultStr();
      resultStr = resultStr.replaceAll(",", "");
      
      // 还没开奖
      if ("XXXXXXXXXXXXXX".equals(resultStr))
      {
        continue;
      }
      
      Entry entry = new Entry();
      entry.index = index;
      index++;
      entry.periodNo = fbl.getPeriodNo();
      
      int hit = 0;
      int miss = 0;
      List gameList = fbl.getGames();
      Iterator gameIt = gameList.iterator();
      while (gameIt.hasNext())
      {
        GameItem game = (GameItem) gameIt.next();
        int orderNo = game.getOrderNo();
        char result = resultStr.charAt(orderNo - 1);
        double winRate = game.getWinCompensationRate();
        double drawRate = game.getDrawCompensationRate();
        double lostRate = game.getLostCompensationRate();
        
        if ((winRate <= drawRate && winRate <= lostRate && result == '3') 
            || (drawRate <= winRate && drawRate <= lostRate && result == '1')
            || (lostRate <= winRate && lostRate <= drawRate && result == '0'))
        {
          hit++;
        }
        else
        {
          miss++;
        }
      }
      entry.hit = hit;
      entry.miss = miss;
      list.add(entry);
    }
    return list;
  }

  private void addRows(List entryList)
  {
    DefaultTableModel model = (DefaultTableModel) this.jTable1.getModel();
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(JLabel.CENTER);
    jTable1.setDefaultRenderer(Object.class, renderer);

    int hitTotal = 0;
    int missTotal = 0;
    
    Iterator it = entryList.iterator();
    while (it.hasNext())
    {
      Entry entry = (Entry) it.next();
      hitTotal += entry.hit;
      missTotal += entry.miss;
      model.addRow(new Object[]{entry.index, entry.periodNo, entry.type, entry.hit, entry.miss});
    }
    double hitAvg = ((double)hitTotal) / entryList.size();
    double missAvg = ((double)missTotal) / entryList.size();
    
    this.hitAvgLabel.setText(hitAvg + "");
    this.missAvgLabel.setText(missAvg + "");
  }

  private void displayBarChart(List entryList)
  {
    if (this.chartFrame != null)
    {
      RefineryUtilities.centerFrameOnScreen(chartFrame);
      chartFrame.setVisible(true);
      return;
    }
    
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    
    Collections.sort(entryList);
    Iterator it = entryList.iterator();
    while (it.hasNext())
    {
      Entry entry = (Entry) it.next();
      dataset.addValue(entry.hit, "Hit", new Integer(entry.periodNo));
      // dataset.addValue(entry.miss, "Miss", new Integer(entry.periodNo));
    }
    
    JFreeChart chart = ChartFactory.createBarChart3D("Hit And Miss", "Period No.", "Hit No.", dataset, 
        PlotOrientation.VERTICAL, true, true, false);
    
    chartFrame = new ChartFrame("Hit Bar Chart", chart, true);
    chartFrame.setSize(1000, 500);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    CategoryAxis axis = plot.getDomainAxis();
    NumberAxis numAxis = (NumberAxis) plot.getRangeAxis();
    numAxis.setTickUnit(new NumberTickUnit(1D));
    axis.setCategoryMargin(0.5);
    axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
    GradientPaint gradientpaint = new GradientPaint(0.0F, 0.0F, Color.blue, 0.0F, 0.0F, new Color(0, 64, 0));
    BarRenderer3D renderer=(BarRenderer3D) plot.getRenderer();
    renderer.setSeriesPaint(0, gradientpaint);
    RefineryUtilities.centerFrameOnScreen(chartFrame);
    chartFrame.setVisible(true);
  }
  
  class Entry implements Comparable
  {
    int index;
    int periodNo;
    int hit;
    int miss;
    String type;

    @Override
    public int compareTo(Object o)
    {
      Entry entry = (Entry) o;
      return (new Integer(this.periodNo)).compareTo((new Integer(entry.periodNo)));
    }
  }
}
